package com.jsnj33.pdaproject.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jsnj33.pdaproject.R;
import com.jsnj33.pdaproject.adapter.FormAdapter;
import com.jsnj33.pdaproject.adapter.FormHorizontalAdapter;
import com.jsnj33.pdaproject.base.BaseActivity;
import com.jsnj33.pdaproject.bean.BatchAndProductBean;
import com.jsnj33.pdaproject.bean.FormGoodsBean;
import com.jsnj33.pdaproject.bean.MainBean;
import com.jsnj33.pdaproject.bean.MsgBean;
import com.jsnj33.pdaproject.constant.Constants;
import com.jsnj33.pdaproject.utils.SaNetUtils;
import com.jsnj33.pdaproject.utils.StringUtility;
import com.jsnj33.pdaproject.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.StringEntity;

public class GZ_FormActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "FormActivity";
    private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action

    private Vibrator mVibrator;
    private ScanManager mScanManager;
    private SoundPool soundpool = null;
    private int soundid;
    private boolean isScaning = false;
    private Button btnRetryScan;
    private TextView title;
    private TextView tvOrder;
    private RelativeLayout rProgressBar;
    private TextView tv_gh_no;

    private AlertDialog dialog;
    private FormAdapter adapter;
    private List<FormGoodsBean> list = new ArrayList<>();
    private List<MainBean> listAdress;
    private String tailUrl;
    private String oldTailUrl;
    private String os_no = "";
    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            isScaning = false;
            soundpool.play(soundid, 1, 1, 0, 0, 1);
            mVibrator.vibrate(100);

            byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            String str = new String(barcode, 0, barcodelen);
            if (StringUtility.isEmpty(str)) {
                ToastUtil.showGravityToast(GZ_FormActivity.this, "扫码失败！", Gravity.CENTER, 0, 0);
                return;
            }
            String sbs = str.substring(0, 2);
            switch (sbs) {
                //扫描货品码
                case "MO":
                case "TY":
                case "TP":
                    //作为制令单处理
                    setGoodsData(str);
                    os_no = str;
                    break;
                case "ht":
                    scanningProductName(str);
                    break;
                default:
                    tv_gh_no.setText(str);
                    break;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_form_gz);
        btnRetryScan = findViewById(R.id.btnRetryScan);
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initScan();
        IntentFilter filter = new IntentFilter();
        int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
        String[] value_buf = mScanManager.getParameterString(idbuf);
        if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
            filter.addAction(value_buf[0]);
        } else {
            filter.addAction(SCAN_ACTION);
        }

        registerReceiver(mScanReceiver, filter);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mScanManager != null) {
            mScanManager.stopDecode();
            isScaning = false;
        }
        unregisterReceiver(mScanReceiver);
    }

    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.openScanner();

        mScanManager.switchOutputMode(0);
        soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        soundid = soundpool.load("/etc/Scan_new.ogg", 1);
    }

    private void initData() {
        title = findViewById(R.id.title);
        tv_gh_no = findViewById(R.id.tv_gh_no);
        rProgressBar = findViewById(R.id.rProgressBar);
        RecyclerView rvHorizontal = findViewById(R.id.recyclerview_horizontal);
        RecyclerView rvVertical = (RecyclerView) findViewById(R.id.recyclerview_vertical);
        tvOrder = (TextView) findViewById(R.id.tv_order);
        Button submit = (Button) findViewById(R.id.submit);

        tvOrder.setOnClickListener(this);
        submit.setOnClickListener(this);

        Intent intent = getIntent();
        if (intent != null) {
            title.setText(getIntent().getStringExtra("title"));
            listAdress = (List<MainBean>) getIntent().getSerializableExtra("list");
            tailUrl = listAdress.get(0).getAddress();
            oldTailUrl = tailUrl;
        }
        rvHorizontal.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        rvHorizontal.setNestedScrollingEnabled(false);//禁止滑动
        FormHorizontalAdapter adapterHorizontal = new FormHorizontalAdapter(this) {
            @Override
            protected void itemChick(String address) {
                tailUrl = address;

            }
        };
        rvHorizontal.setAdapter(adapterHorizontal);
        adapterHorizontal.setList(listAdress);


        initRecyclerView(rvVertical, LinearLayoutManager.VERTICAL);
        btnRetryScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                removeInfo();
            }
        });
    }

    private void initRecyclerView(RecyclerView recyclerView, int vertical) {
        recyclerView.setLayoutManager(new LinearLayoutManager(this, vertical, false));
        recyclerView.setNestedScrollingEnabled(false);//禁止滑动
        adapter = new FormAdapter(this);
        recyclerView.setAdapter(adapter);
    }

    private void fillInData(final List<FormGoodsBean> controlList, final String osNo, final String num) {

        final AlertDialog.Builder builder = new AlertDialog.Builder(GZ_FormActivity.this);
        View view = LayoutInflater.from(GZ_FormActivity.this).inflate(R.layout.popup_number_view, null);
        builder.setView(view);
        //这个位置十分重要，只有位于这个位置逻辑才是正确的
        dialog = builder.show();
        dialog.setTitle("请输入数量");
        final EditText etNumber = view.findViewById(R.id.et_number);
        etNumber.setSelection(num.length());
        view.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                FormGoodsBean bean = controlList.get(0);
                try {
                    controlList.get(0).setSmqty(Double.valueOf(etNumber.getText().toString()));
                    bean.setSmqty(Double.valueOf(etNumber.getText().toString() + ""));
                } catch (Exception e) {
                    bean.setSmqty(Double.valueOf("0"));
                    controlList.get(0).setSmqty(Double.valueOf("0"));
                    Log.i(TAG, "onClick: " + e.getMessage());
                }
                list.addAll(controlList);
                tvOrder.setText(osNo);//设置制令单号
                adapter.setList(list, true);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.submit:
                submitData();
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
     * prd_no:扫到的货品码
     * mo_no:制令单号
     * qty:实缴数
     * user：作业人员
     * wh:仓库
     */
    private void submitData() {
        String os_no = tvOrder.getText().toString();
        String user = tv_gh_no.getText().toString();
        boolean b = judgeString(os_no, user);
        if (b == true) {
            ToastUtil.showGravityToast(GZ_FormActivity.this, "信息不全无法提交！", Gravity.CENTER, 0, 0);
            return;
        }

        if (tailUrl.equals(listAdress.get(0).getAddress())) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setOs_no(os_no);
            }
        }


        Map<String, Object> map = new HashMap<>();
        map.put("table", listAdress.get(0).getCodeName());
        map.put("tablename", title.getText().toString());
        map.put("os_no", os_no);
        map.put("usr", user);
        map.put("User", tv_gh_no.getText() + "");
        map.put("list", list);
        String url = Constants.SUBMIT_ZANGU;
        getHttpData(url, map);
    }

    private void getHttpData(final String url, Map<String, Object> map) {
        rProgressBar.setVisibility(View.VISIBLE);
        RequestParams requestParams = new RequestParams(url);
        String gson = new Gson().toJson(map);
        requestParams.setBodyContent(gson);
        requestParams.setAsJsonContent(true);
        x.http().post(requestParams, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                try {
                    Log.d(TAG, "getHttpData-onSuccess: " + jsonObject.toString());
                    int errCode = jsonObject.getInt("errCode");
                    String msg = jsonObject.getString("errMsg");
                    if (errCode == -1) {
                        ToastUtil.showLongGravityToast(GZ_FormActivity.this, msg, Gravity.CENTER, 0, 0);
                    } else {
                        //请求成功
                        removeInfo();
                        ToastUtil.showToast(GZ_FormActivity.this, "提交成功");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i(TAG, "Exception: " + e.getMessage());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                rProgressBar.setVisibility(View.GONE);
            }
        });
    }

    /**
     * 扫描制令单号
     *
     * @param osNo
     */
    private void setGoodsData(final String osNo) {
        AsyncHttpClient client = SaNetUtils.getAsyncHttpClient();
        String url = Constants.SCANNING_PRODUCT_CODE + tailUrl;
        final JSONObject map = new JSONObject();
        try {
            map.put("os_no", osNo);
            map.put("User", tv_gh_no.getText() + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            StringEntity stringEntity = new StringEntity(map.toString());
            stringEntity.setContentType("application/json");
            client.post(this, url, stringEntity, "application/json", new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                    super.onSuccess(statusCode, headers, response);
                    String str = new String(response.toString());
                    Log.i(TAG, "onSuccess: " + str);
                    try {
                        List<FormGoodsBean> controlList = new Gson().fromJson(str, new TypeToken<List<FormGoodsBean>>() {
                        }.getType());

                        if (oldTailUrl.equals(tailUrl)) {
                            if (tailUrl.equals(listAdress.get(0).getAddress())) {
//                                fillInData(controlList, osNo);
//                                adapter.setList(list, true);
                                list = controlList;
                                tvOrder.setText(osNo);//设置制令单号
                                adapter.setList(controlList, true);
                                return;
                            } else {
                                list = controlList;
                                tvOrder.setText(osNo);//设置制令单号
                                adapter.setList(controlList, true);
                            }
                        } else {
                            removeInfo();
                            list = controlList;
                            tvOrder.setText(osNo);//设置制令单号
                            oldTailUrl = tailUrl;
                        }

                        for (int i = 0; i < list.size(); i++) {
                            FormGoodsBean bean = list.get(i);
                            bean.setSmqty(bean.getQty());
                        }

                        adapter.setList(list, true);
                    } catch (Exception e) {
                        try {
                            List<MsgBean> msgBean = new Gson().fromJson(str, new TypeToken<List<MsgBean>>() {
                            }.getType());
                            MsgBean bean = msgBean.get(0);
                            int errCode = bean.getErrCode();
                            String msg = bean.getErrMsg();
                            if (errCode == -1) {
                                ToastUtil.showLongGravityToast(GZ_FormActivity.this, msg, Gravity.CENTER, 0, 0);
                            }
                        } catch (Exception ex) {
                            ToastUtil.showLongGravityToast(GZ_FormActivity.this, "服务器出错！！", Gravity.CENTER, 0, 0);
                        }
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    super.onFailure(statusCode, headers, throwable, errorResponse);
                    ToastUtil.showGravityToast(GZ_FormActivity.this, throwable.getMessage(), Gravity.CENTER, 0, 0);
                    Log.i(TAG, "onFailure: " + throwable.getMessage());
                }

            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void scanningProductName(final String barcode) {

        boolean b = judgeString(barcode);
        if (b == true) {
            ToastUtil.showGravityToast(GZ_FormActivity.this, "二维码不存在！！！", Gravity.CENTER, 0, 0);
            return;
        }

        AsyncHttpClient client = SaNetUtils.getAsyncHttpClient();
        String url = Constants.SCANNING_PRODUCT_NAME_ZANGU;
        final JSONObject map = new JSONObject();
        try {
            map.put("os_no", os_no);
            map.put("barcode", barcode);
            map.put("User", tv_gh_no.getText() + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try {
            StringEntity stringEntity = new StringEntity(map.toString());
            stringEntity.setContentType("application/json");
            client.post(this, url, stringEntity, "application/json", new JsonHttpResponseHandler() {

                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    super.onSuccess(statusCode, headers, response);
                    String str = new String(response.toString());
                    try {
                        BatchAndProductBean beans = new Gson().fromJson(str, BatchAndProductBean.class);

                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getPrd_no().equals(beans.getPrd_no())
                                    && list.get(i).getBat_no().equals(beans.getBat_no())) {
                                fillInData(i, barcode, beans.getBat_no(), beans.getSmqty() + "");
                                return;
                            }
                        }

                        ToastUtil.showLongGravityToast(GZ_FormActivity.this, "未找到此条数据", Gravity.CENTER, 0, 0);

                    } catch (Exception e) {
                        try {
                            List<MsgBean> msgBean = new Gson().fromJson(str, new TypeToken<List<MsgBean>>() {
                            }.getType());
                            MsgBean bean = msgBean.get(0);
                            int errCode = bean.getErrCode();
                            String msg = bean.getErrMsg();
                            if (errCode == -1) {
                                ToastUtil.showLongGravityToast(GZ_FormActivity.this, msg, Gravity.CENTER, 0, 0);
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                    super.onFailure(statusCode, headers, throwable, errorResponse);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void fillInData(final int position, final String barcode, final String batNo, final String num) {
        if (dialog != null && dialog.isShowing()) {
            return;
        }
        final AlertDialog.Builder builder = new AlertDialog.Builder(GZ_FormActivity.this);
        View view = LayoutInflater.from(GZ_FormActivity.this).inflate(R.layout.popup_number_view, null);
        builder.setView(view);
        //这个位置十分重要，只有位于这个位置逻辑才是正确的
        dialog = builder.show();
        dialog.setTitle("请输入数量");
        final EditText etNumber = view.findViewById(R.id.et_number);
        etNumber.setText(num);
        etNumber.setSelection(num.length());
        view.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }

                FormGoodsBean bean = list.get(position);

                bean.setSmqty(Double.parseDouble(etNumber.getText().toString()));
                bean.setBarcode(barcode);

                if (!listAdress.get(0).getAddress().equals(oldTailUrl)) {
                    bean.setBat_no(batNo);
                }
                adapter.setList(list, true);
            }
        });
    }


    /**
     * 提交数据后清空数据
     */
    private void removeInfo() {
        clearText(tvOrder);
        list = new ArrayList<>();
        adapter.setList(list, false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeInfo();
    }

    private void clearText(TextView... textViews) {
        for (int i = 0; i < textViews.length; i++) {
            textViews[i].setText("");
        }
    }

    /**
     * 判断必传参数中是否有null或者""。
     *
     * @param str
     * @return true:有  false:无
     */
    private boolean judgeString(String... str) {
        for (int i = 0; i < str.length; i++) {
            if (StringUtility.isEmpty(str[i])) {
                return true;
            }
        }
        return false;
    }
}
